package com.ssm.anno.config;

import com.ssm.anno.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张富玮
 * @create 2022-01-29 9:59
 */
@Configuration // 指定为配置类
@ComponentScan("com.ssm.anno.controller") // 组件扫描
@EnableWebMvc // 开启 SpringMVC 注解驱动
public class WebConfig implements WebMvcConfigurer {

    /**
     * 开启默认处理器处理静态资源
     *
     * @param configurer
     */
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 配置拦截器
     *
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        LoginInterceptor loginInterceptor = new LoginInterceptor();
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }

    /**
     * 配置响应中文乱码
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter messageConverter = new StringHttpMessageConverter();

        messageConverter.setDefaultCharset(StandardCharsets.UTF_8);

        List<MediaType> mediaTypes = new ArrayList<MediaType>();
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON);

        messageConverter.setSupportedMediaTypes(mediaTypes);

        converters.add(messageConverter);
    }

    /**
     * 配置文件上传
     *
     * @return
     */
    @Bean
    public MultipartResolver getMultipartResolver() {
        return new CommonsMultipartResolver();
    }
}
